'use client'

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { Sheet } from '@/types/sheet'
import { sheetsApi } from '@/lib/api/sheets'
import { useAuth } from './AuthContext'

interface SheetsContextType {
  sheets: Sheet[]
  loading: boolean
  error: string | null
  fetchSheets: (forceRefresh?: boolean) => Promise<void>
  addSheet: (sheet: Sheet) => void
  removeSheet: (sheetId: string) => void
  updateSheet: (sheet: Sheet) => void
}

const SheetsContext = createContext<SheetsContextType | undefined>(undefined)

interface SheetsProviderProps {
  children: ReactNode
}

export const SheetsProvider: React.FC<SheetsProviderProps> = ({ children }) => {
  const { user } = useAuth()
  const [sheets, setSheets] = useState<Sheet[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 获取表格列表
  const fetchSheets = async (forceRefresh = false) => {
    if (!user) return
    
    // 如果已经有数据且不是强制刷新，则跳过
    if (sheets.length > 0 && !forceRefresh) {
      return
    }
    
    try {
      setLoading(true)
      setError(null)
      const response = await sheetsApi.getUserSheets()
      setSheets(response.data || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }

  // 添加表格
  const addSheet = (sheet: Sheet) => {
    setSheets(prev => [sheet, ...prev])
  }

  // 删除表格
  const removeSheet = (sheetId: string) => {
    setSheets(prev => prev.filter(sheet => sheet.id !== sheetId))
  }

  // 更新表格
  const updateSheet = (updatedSheet: Sheet) => {
    setSheets(prev => prev.map(sheet => 
      sheet.id === updatedSheet.id ? updatedSheet : sheet
    ))
  }

  // 初始加载
  useEffect(() => {
    if (user) {
      fetchSheets()
    } else {
      // 用户登出时清空数据
      setSheets([])
      setLoading(false)
      setError(null)
    }
  }, [user])

  const value: SheetsContextType = {
    sheets,
    loading,
    error,
    fetchSheets,
    addSheet,
    removeSheet,
    updateSheet
  }

  return (
    <SheetsContext.Provider value={value}>
      {children}
    </SheetsContext.Provider>
  )
}

export const useSheets = (): SheetsContextType => {
  const context = useContext(SheetsContext)
  if (context === undefined) {
    throw new Error('useSheets must be used within a SheetsProvider')
  }
  return context
}
